package cn.starrysky.hrm.Interceptor;

import cn.starrysky.hrm.util.HttpUtil;
import cn.starrysky.hrm.utils.ValidUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

//Fiegn拦截器
@Component
@Slf4j
public class DefaultOAuth2FeignRequestInterceptor implements RequestInterceptor {

    //请求头中的token
    private final String AUTHORIZATION_HEADER = "Authorization";

    @Value("${auth.client.tokenurl}")
    private String TEMP_TOKEN_URL;
    @Value("${auth.client.clientid}")
    private String clientid;
    @Value("${auth.client.secret}")
    private String secret;


    @Override
    public void apply(RequestTemplate requestTemplate) {
        //"http://localhost:${server.port}/oauth/token?client_id=%s&client_secret=%s&grant_type=client_credentials"
        //1.基于客户端模式创建token
        String url = String.format(TEMP_TOKEN_URL,clientid,secret);

        //2.post请求
        Map<String, String> tokenMap = HttpUtil.sendPost(url);
        ValidUtils.assertNotNull(tokenMap,"服务调用失败[临时Token获取失败]");
        String token ="Bearer "+ tokenMap.get("access_token");
        //3.把令牌添加到Fiegn的请求头
        requestTemplate.header(AUTHORIZATION_HEADER, token);
        log.info("Feign拦截器添加请求头：{}",token);
    }

}